import { MouseEvent, memo } from 'react'
import styles from './index.module.scss'
import { Spin } from 'antd'
import useGetComponentInfo from '@/hooks/useGetComponentInfo'
import useBindCanvasKeyPress from '@/hooks/useBindCanvasKeyPress'
import { getComponentConfByType } from '@/components/QuestionComponents'
import { ComponentInfoType, moveComponent } from '@/store/modules/componentsReducer'
import { useDispatch } from 'react-redux'
import { changeSelectedId } from '@/store/modules/componentsReducer'
import classNames from 'classnames'
import SortableContainer from '@/components/DragSortable/SortableContainer'
import SortableItem from '@/components/DragSortable/SortableItem'

type PropsType = {
  loading: boolean
}

const getComponent = (componentInfo: ComponentInfoType) => {
  const { type, props } = componentInfo
  const Component = getComponentConfByType(type)?.component as any
  return <Component {...props} />
}

const EditCanvas = memo(({ loading }: PropsType) => {
  const { componentList, selectedId } = useGetComponentInfo()

  useBindCanvasKeyPress()

  const dispatch = useDispatch()
  const handleClick = (event: MouseEvent, id: string) => {
    event.stopPropagation()
    dispatch(changeSelectedId(id))
  }

  if (loading) {
    return (
      <div style={{ textAlign: 'center', marginTop: '50%' }}>
        <Spin />
      </div>
    )
  }

  const componentListWithId = componentList.map((item: ComponentInfoType) => {
    return {
      id: item.fe_id,
      ...item,
    }
  })

  const handleDragEnd = (oldIndex: number, newIndex: number) => {
    dispatch(moveComponent({ oldIndex, newIndex }))
  }

  return (
    <SortableContainer items={componentListWithId} onDragEnd={handleDragEnd}>
      <div className={styles.canvas}>
        {componentList
          .filter((c: ComponentInfoType) => !c.isHidden)
          .map((c: ComponentInfoType) => {
            const { fe_id } = c
            const wrapperDefaultClass = styles['component-wrapper']
            const selectedClass = styles.selected
            const lockedClass = styles.locked

            const wrapperClass = classNames(wrapperDefaultClass, {
              [selectedClass]: selectedId === fe_id,
              [lockedClass]: c.isLocked,
            })

            return (
              <SortableItem key={fe_id} id={fe_id}>
                <div className={wrapperClass} onClick={e => handleClick(e, fe_id)}>
                  <div className={styles.component}>{getComponent(c)}</div>
                </div>
              </SortableItem>
            )
          })}
      </div>
    </SortableContainer>
  )
})

export default EditCanvas
